package com.juyu.miliao.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author jh
 * 2018/10/7
 */
public class IpUtil {

    private static Logger logger = LoggerFactory.getLogger(IpUtil.class);
    private static final int outTime = 5000;
    private static final int socketTimeOut = 5000;

    private IpUtil() {
        throw new RuntimeException("illegal new util class");
    }

    /**
     * 获取Ip地址
     *
     * @param request HttpServletRequest
     * @return ip
     */
    public static String getIPv4Address(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if (index != -1) {
                return XFor.substring(0, index);
            } else {
                return XFor;
            }
        }
        XFor = Xip;
        if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }

//    public static String getCountryByIp(String ip){
//
//        String url = "http://ip-api.com/json/"+ip+"?lang=zh-CN";
//        String result = httpGetUtil(url);
//        if(org.apache.commons.lang.StringUtils.isNotBlank(result)){
//            JSONObject json = JSONObject.parseObject(result);
//            return json.getString("country");
//        }else{
//            return "";
//        }
//    }

    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     * @param url
     * @return
     * @throws IOException
     */
//    public static String httpGetUtil(String url){
//        //设置请求和传输超时时间
//        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeOut)
//                .setConnectTimeout(outTime).build();
//        HttpGet get = new HttpGet(url);
//        get.setConfig(requestConfig);
//
//        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
//            CloseableHttpResponse response = httpClient.execute(get);
//            // 判断状态码是否为200
//            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                // 返回响应体的内容
//                return EntityUtils.toString(response.getEntity(), "UTF-8");
//            }
//        } catch (Exception e) {
//            logger.error("http请求错误：" + e.getMessage());
//        }
//        return null;
//    }

}